package com.action;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.pojo.UserInfo;
import com.pojo.Xiaofei;
import com.service.UserInfoService;
import com.service.XiaofeiService;
import com.util.StringUtil;
import com.vo.XiaofeiVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/xf")
public class XiaofeiAction {

    @Autowired
    private XiaofeiService xfService;

    @Autowired
    private UserInfoService staffService;

    @Value("${upload.dir}")
    private String upload ;

    /**
     * 根据卡号获取用户信息
     */
    @RequestMapping("/getStaffInfo")
    public ResponseBean getStaffInfo(String cardNo, HttpServletRequest request) {
        String queryStr = null;
        Map<String,Object> resultMap = staffService.getStaffInfoByCz(cardNo, queryStr);
        if (null == resultMap) {
            return new ResponseBean(0,1,"会员不存在","该卡没有绑定会员");
        }
        return new ResponseBean(1,1,"读取成功",resultMap);
    }

    /**
     * 消费
     * @param xf
     * @return
     */
    @RequestMapping("/saveXf")
    @ResponseBody
    public ResponseBean saveXf(@RequestBody Xiaofei xf) {
        Xiaofei saveXf = new Xiaofei();
        saveXf.setCardNo(xf.getCardNo());
        saveXf.setPin(xf.getPin());
        BigDecimal xfAmount = xf.getXfAmount();
        BigDecimal balance = xf.getStaffBalance();
        saveXf.setXfAmount(xfAmount);
        saveXf.setStaffBalance(balance.subtract(xfAmount));
        saveXf.setStaffId(xf.getStaffId());
        saveXf.setXfTime(new Date());
        int c = xfService.saveXf(saveXf);
        UserInfo staff = new UserInfo();
        staff.setId(xf.getStaffId());
        staff.setCardBalance(balance.subtract(xfAmount));
        boolean updFlag = staffService.updateById(staff);
        if (c != 1 && !updFlag) {
            return new ResponseBean(0,1, "消费失败");
        }
        return new ResponseBean(1,1, "消费成功");
    }
    /**
     * 获取用户消费记录
     */
    @RequestMapping("/getXfByUser")
    public ResponseBean getXfByUser(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, String staffId, @RequestParam(required = false) String start_time, @RequestParam(required = false) String end_time) {
        if(StringUtil.isNull(start_time)){
            start_time=null;
        }
        if(StringUtil.isNull(end_time)){
            end_time=null;
        }
        IPage<XiaofeiVo> xfList = xfService.getCzRecordByUser(page,limit,staffId,start_time,end_time);
        return new ResponseBean(0, xfList.getTotal(), "成功", xfList.getRecords());
    }

    /**
     * 获取消费记录
     */
    @RequestMapping("/getXfRecord")
    public ResponseBean getXfRecord(String staffName, int page, int limit, @RequestParam(required = false) String start_time, @RequestParam(required = false) String end_time) {
        String queryStr = null;
        if(StringUtil.isNull(start_time)){
            start_time=null;
        }
        if(StringUtil.isNull(end_time)){
            end_time=null;
        }
        if(StringUtil.isNull(staffName)){
            staffName=null;
        }
        IPage iPage = xfService.getXfRecord(page,limit,staffName,start_time,end_time, queryStr);
        return new ResponseBean(0, iPage.getTotal(), "成功", iPage.getRecords());
    }

    /**
     * 导出Excel
     */
    @RequestMapping("/exportExcelByXf")
    public ResponseEntity<InputStreamResource> exportExcelByXf(String staffName, @RequestParam(required = false) String start_time, @RequestParam(required = false) String end_time) throws IOException {
        String queryStr = null;

        if(StringUtil.isNull(start_time)){
            start_time=null;
        }
        if(StringUtil.isNull(end_time)){
            end_time=null;
        }
        if(StringUtil.isNull(staffName)){
            staffName=null;
        }
        List<XiaofeiVo> xfList = xfService.exportByExecl(staffName,start_time,end_time, queryStr);
        String cnFileName = new String("消费记录".getBytes(), "utf-8");
        String name = cnFileName + new Date().getTime() + ".xls" ;
        String fileName = upload + "/excel/" + name ;
        if(!new File(upload + "/excel/").exists()) {
            new File(upload + "/excel/").mkdirs() ;
        }
        try {
//            ExcelUtil.exportExcelByCz(fileName,"消费记录",xfList,"xf");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource (fileName) ;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
}
